package org.breathe.command.impl.string;

import lombok.extern.slf4j.Slf4j;
import org.breathe.command.Command;
import org.breathe.command.CommandType;
import org.breathe.datastruct.RedisBytes;
import org.breathe.datastruct.RedisData;
import org.breathe.datastruct.impl.RedisString;
import org.breathe.protocal.Resp;
import org.breathe.protocal.decode.BulkString;
import org.breathe.protocal.decode.Errors;
import org.breathe.server.core.RedisCore;

/**
 * @author: breathe
 * @createTime: 2025-05-12
 */
@Slf4j
public class Get implements Command {
    private RedisCore redisCore;
    private RedisBytes key;
    public Get(RedisCore redisCore) {
        this.redisCore = redisCore;
    }
    @Override
    public CommandType getType() {
        return CommandType.GET;
    }

    @Override
    public void setContext(Resp[] array) {
        key = ((BulkString)array[1]).getContent();
    }

    @Override
    public Resp handle() {
        try {
            RedisData data = redisCore.get(key);
            if (data == null) {
                return new BulkString(BulkString.NULL);
            }
            if (data instanceof RedisString redisString) {
                return new BulkString(redisString.getValue());
            }
        } catch(Exception e) {
            log.error("handler error", e);
            return new Errors("ERR internal server error");
        }
        return new Errors("ERR unknown error");
    }

    @Override
    public boolean writeCommand() {
        return false;
    }
}
